import React, { useEffect, useState } from "react";
import { Space, Table, Button, message, Input, Modal, Form, Switch } from "antd";
import type { TableProps } from "antd";
import http from "../../utils/http";
// 类型
interface AddressType {
  id: string;
  addrescity: string;
  addresdesc: string;
  addresname: string;
  addresphone: string;
  addresstate: string;
}

const Index: React.FC = () => {
  // 数据
  const [datalist, setDatalist] = useState([]);
  const [originalDatalist, setOriginalDatalist] = useState<AddressType[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const { Search } = Input;
  const [searchValue, setSearchValue] = useState("");
  const columns: TableProps<AddressType>["columns"] = [
    {
      title: (
        <div>
          ID
        </div>
      ),
      align: "center",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "城市",
      align: "center",
      dataIndex: "addrescity",
      key: "addrescity",
    },
    {
      title: "详细地址",
      align: "center",
      dataIndex: "addresdesc",
      key: "addresdesc",
    },
    {
      title: "收货人",
      align: "center",
      dataIndex: "addresname",
      key: "addresname",
    },
    {
      title: "手机号",
      align: "center",
      dataIndex: "addresphone",
      key: "addresphone",
    },
    {
      title: "地址状态",
      align: "center",
      dataIndex: "addresstate",
      key: "addresstate",
      render: () => {
        return (
          <Switch defaultChecked onChange={onChange} />
        );
      },
    },
    {
      title: "操作",
      align: "center",
      key: "doctorid",
      render: (record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => EditshowModal(record)}>
            编辑
          </Button>
          <Button type="primary" danger onClick={() => hanDel(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];
  // 开关状态
  const onChange = (checked: boolean) => {
    console.log(`switch to ${checked}`);
  };
  // 渲染数据
  const FearchList = async () => {
    const res = await http.get("/address/list");
    const { code, data } = res.data;
    if (code === 20000) {
      setDatalist(data);
      setOriginalDatalist(data);
    }
  };
  useEffect(() => {
    FearchList();
  }, []);
  // 删除数据
  const hanDel = async (record: AddressType) => {
    const res = await http.delete(`/address/delete?id=${record.id}`);
    const { code } = res.data;
    if (code === 20000) {
      message.success("删除成功");
      FearchList();
    }
  };
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [DialogState, setDialogState] = useState(true);
  const [editedRecord, setEditedRecord] = useState<AddressType | null>(null);
  // 编辑/添加
  const AddshowModal = () => {
    form.resetFields();
    setIsModalOpen(true);
    setDialogState(true);
    setEditedRecord(null);
  };
  const EditshowModal = (record: AddressType) => {
    form.setFieldsValue(record);
    setIsModalOpen(true);
    setDialogState(false);
    setEditedRecord(record);
  };

  const handleOk = async () => {
    if (DialogState) {
      // 新增逻辑
      try {
        const values = form.getFieldsValue();
        const res = await http.put("/address/add", {
          name: values.addresname,
          phone: values.addresphone,
          city: values.addrescity,
          desc: values.addresdesc,
          state: values.addresstate,
        });
        const { code } = res.data;
        if (code === 20000) {
          message.success("新增成功");
          FearchList();
        } else {
          message.error("新增失败");
        }
      } catch (error) {
        console.error(error);
        message.error("新增失败");
      }
    } else {
      // 编辑逻辑
      try {
        const values = form.getFieldsValue();
        const res = await http.post(`/address/update/`, {
          name: values.addresname,
          phone: values.addresphone,
          city: values.addrescity,
          desc: values.addresdesc,
          state: values.addresstate,
          id: values.id,
        });

        const { code } = res.data;
        if (code === 20000) {
          message.success("编辑成功");
          FearchList();
        } else {
          message.error("编辑失败");
        }
      } catch (error) {
        console.error(error);
        message.error("编辑失败");
      }
    }
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // 查询
  const onSearch = (value: string) => {
    setSearchValue(value);
    if (!value) {
      setDatalist(originalDatalist);
    } else {
      const filteredData = originalDatalist.filter((item) =>
        Object.values(item).some((v) =>
          String(v).toLowerCase().includes(value.toLowerCase())
        )
      );
      setDatalist(filteredData);
    }
  };
  return (
    <div>
      <div>
        <Button
          type="primary"
          style={{ marginRight: "60px" }}
          onClick={() => AddshowModal()}
        >
          增加数据
        </Button>
        <Search
          placeholder="请输入搜索内容"
          allowClear
          enterButton="搜索"
          size="small"
          style={{ width: "300px" }}
          onSearch={onSearch}
        />
      </div>

      <Table<AddressType>
        rowKey={"id"}
        rowSelection={{
          onChange(newSelectedRowKeys: React.Key[]) {
            console.log(newSelectedRowKeys);
            setSelectedRowKeys(newSelectedRowKeys);
          },
        }}
        columns={columns}
        dataSource={datalist}
      />
      {/* 添加编辑和增加弹框 */}
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} name="control - hooks" style={{ maxWidth: 600 }}>
          <Form.Item name="id" label="ID" >
            <Input disabled />
          </Form.Item>
          <Form.Item
            name="addrescity"
            label="城市"
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="addresdesc"
            label="详细地址"
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="addresname"
            label="收货人"
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="addresphone"
            label="手机号"
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="addresstate"
            label="地址状态"
          >
            <Switch defaultChecked onChange={onChange} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Index;